package cn.py.boot_lua.handler;

import cn.py.boot_lua.handler.admin.RequestTask;
import cn.py.boot_lua.handler.generic.GenericQueueService;
import cn.py.boot_lua.handler.generic.QueueType;
import cn.py.boot_lua.handler.impl.ImageBackServiceImpl;
import cn.py.boot_lua.util.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

@Component
public class BackgroundImageTaskHandler {
    private static final Logger log = LoggerFactory.getLogger(BackgroundImageTaskHandler.class);
    private final Semaphore semaphore = new Semaphore(2);
    @Autowired
    private GenericQueueService genericQueueService;
    @Autowired
    private ImageBackServiceImpl imageBackService;

   // @Scheduled(fixedRate = 1000)
    public void process() {
        try {
            RequestTask task = genericQueueService.pollFromQueue(QueueType.BACK_IMG.getKey());
            if (task != null) {
                semaphore.acquire();
                log.info("图像背景获取信号量许可: {}", task.getRequestId());
                try {
                    imageBackService.backImgHandleAsync(task, () -> {
                        log.info("图像背景生成任务ID: {} 处理完成", task.getRequestId());
                        semaphore.release();
                    });
                } catch (Exception e) {
                    log.error("提交图像背景任务失败: {}", task.getRequestId(), e);
                }finally {
                    semaphore.release();
                }
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.warn("任务处理被中断", e);
        } catch (Exception e) {
            log.error("图像背景生成任务处理过程中发生错误", e);
        }
    }
}
